<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发起委托 - 试验检测系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366f1',
                        secondary: '#8b5cf6',
                        accent: '#06b6d4'
                    }
                }
            }
        }
    </script>
    <style>
        /* 基础样式：保持原设计风格，增加交互反馈 */
        .mt-4 {
            margin-top: 1rem;
        }

        .transition-all {
            transition: all 0.3s ease;
        }

        .duration-300 {
            transition-duration: 300ms;
        }

        .border-2 {
            border-width: 2px;
        }

        .border-dashed {
            border-style: dashed;
        }

        .border-gray-300 {
            border-color: #d1d5db;
        }

        .border-blue-500 {
            border-color: #3b82f6;
        }

        /* 拖拽悬浮时边框色 */
        .bg-blue-50 {
            background-color: #f0f9ff;
        }

        /* 拖拽悬浮时背景色 */
        .rounded-lg {
            border-radius: 0.5rem;
        }

        .p-6 {
            padding: 1.5rem;
        }

        .text-center {
            text-align: center;
        }

        .text-3xl {
            font-size: 1.875rem;
        }

        .text-gray-400 {
            color: #9ca3af;
        }

        .text-gray-600 {
            color: #4b5563;
        }

        .text-sm {
            font-size: 0.875rem;
        }

        .mb-3 {
            margin-bottom: 0.75rem;
        }

        .mt-4 {
            margin-top: 1rem;
        }

        .bg-gray-100 {
            background-color: #f3f4f6;
        }

        .hover\:bg-gray-200:hover {
            background-color: #e5e7eb;
        }

        .text-gray-800 {
            color: #1f2937;
        }

        .py-2 {
            padding-top: 0.5rem;
            padding-bottom: 0.5rem;
        }

        .px-4 {
            padding-left: 1rem;
            padding-right: 1rem;
        }

        .cursor-pointer {
            cursor: pointer;
        }

        .outline-none {
            outline: none;
        }

        /* 隐藏原生图片输入框 */
        #fileInput {
            display: none;
        }

        /* 图片预览区域样式 */
        #previewSection {
            margin-top: 1.5rem;
            display: none;
        }

        .preview-card {
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            padding: 1rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .preview-icon {
            font-size: 1.5rem;
            color: #3b82f6;
        }

        .preview-info {
            flex: 1;
        }

        .preview-name {
            font-weight: 500;
            color: #1f2937;
            margin-bottom: 0.25rem;
        }

        .preview-meta {
            font-size: 0.75rem;
            color: #6b7280;
        }

        .preview-actions {
            color: #ef4444;
            cursor: pointer;
        }

        .preview-actions:hover {
            text-decoration: underline;
        }

        /* 错误提示样式 */
        .error-text {
            color: #ef4444;
            font-size: 0.875rem;
            margin-top: 0.5rem;
            display: none;
        }
    </style>
</head>

<body class="bg-white min-h-screen p-4">
    <div class="max-w-md w-full mx-auto bg-white rounded-3xl shadow-xl overflow-hidden border border-gray-200">
        <!-- Header -->
        <div class="bg-gradient-to-r from-blue-500 to-indigo-600 p-6 text-white text-center">
            <h1 class="text-2xl font-bold">发起委托</h1>
            <p class="text-blue-100 mt-1">请填写委托相关信息</p>
        </div>

        <!-- Form -->
        <form id="delegationForm" class="p-6">
            <!-- 委托单位信息 -->
            <div class="mb-6">
                <div class="flex justify-between items-center pb-2 border-b border-gray-200 cursor-pointer"
                    onclick="toggleSection('unitSection')">
                    <h2 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-building text-blue-500 mr-2"></i> 委托单位信息
                    </h2>
                    <i class="fas fa-chevron-down text-gray-500 transition-transform duration-300"
                        id="unitSection-arrow"></i>
                </div>

                <div class="space-y-4 mt-4 transition-all duration-300" id="unitSection">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            委托单位 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="wtdw" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            委托单位地址 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="wtdwdz" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                委托单位联系人 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="wtdwlxr" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                委托单位电话 <span class="text-red-500">*</span>
                            </label>
                            <input type="tel" name="wtdwdh" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            监理/见证单位
                        </label>
                        <input type="text" name="jljzdw"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            施工单位
                        </label>
                        <input type="text" name="sgdw"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
            </div>

            <!-- 工程信息 -->
            <div class="mb-6">
                <div class="flex justify-between items-center pb-2 border-b border-gray-200 cursor-pointer"
                    onclick="toggleSection('projectSection')">
                    <h2 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-hard-hat text-blue-500 mr-2"></i> 工程信息
                    </h2>
                    <i class="fas fa-chevron-down text-gray-500 transition-transform duration-300"
                        id="projectSection-arrow"></i>
                </div>

                <div class="space-y-4 mt-4 transition-all duration-300" id="projectSection">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            工程名称
                        </label>
                        <input type="text" name="gcmc"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            工程地点
                        </label>
                        <input type="text" name="gcdd"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            工程部位
                        </label>
                        <input type="text" name="gcbw"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
            </div>

            <!-- 样品信息 -->
            <div class="mb-6">
                <div class="flex justify-between items-center pb-2 border-b border-gray-200 cursor-pointer"
                    onclick="toggleSection('sampleSection')">
                    <h2 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-vial text-blue-500 mr-2"></i> 样品信息
                    </h2>
                    <i class="fas fa-chevron-down text-gray-500 transition-transform duration-300"
                        id="sampleSection-arrow"></i>
                </div>

                <div class="space-y-4 mt-4 transition-all duration-300" id="sampleSection">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            取样地点 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="qydd" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                样品名称 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="ypmc" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                取样日期 <span class="text-red-500">*</span>
                            </label>
                            <input type="date" name="qyrq" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                规格型号 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="ggxh" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                样品数量 <span class="text-red-500">*</span>
                            </label>
                            <input type="number" name="ypsl" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                送样编号 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="sybh" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                生产单位
                            </label>
                            <input type="text" name="scdw"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                批号/编号
                            </label>
                            <input type="text" name="phbh"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                代表数量
                            </label>
                            <input type="number" name="dbsl"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 检测信息 -->
            <div class="mb-6">
                <div class="flex justify-between items-center pb-2 border-b border-gray-200 cursor-pointer"
                    onclick="toggleSection('testSection')">
                    <h2 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-clipboard-check text-blue-500 mr-2"></i> 检测信息
                    </h2>
                    <i class="fas fa-chevron-down text-gray-500 transition-transform duration-300"
                        id="testSection-arrow"></i>
                </div>

                <div class="space-y-4 mt-4 transition-all duration-300" id="testSection">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            检测项目 <span class="text-red-500">*</span>
                        </label>
                        <div class="relative">
                            <select name="jcxm" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none">
                                <option value="">请选择检测项目</option>
                                <option>混凝土抗压强度</option>
                                <option>钢筋拉伸试验</option>
                                <option>砂浆抗压强度</option>
                                <option>沥青混合料试验</option>
                                <option>土工试验</option>
                            </select>
                            <div
                                class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                                <i class="fas fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            检测类别
                        </label>
                        <input type="text" name="jclb"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            检测依据
                        </label>
                        <input type="text" name="jcyj"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            评定依据
                        </label>
                        <input type="text" name="pdyj"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            样品处置 <span class="text-red-500">*</span>
                        </label>
                        <textarea name="ypcz" required rows="3"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="请填写样品处置方式..."></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            备注
                        </label>
                        <textarea name="bz" rows="3"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="请输入备注信息..."></textarea>
                    </div>
                </div>
            </div>

            <!-- 附件 -->
            <div class="mb-8">
                <div class="flex justify-between items-center pb-2 border-b border-gray-200 cursor-pointer"
                    onclick="toggleSection('attachmentSection')">
                    <h2 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-paperclip text-blue-500 mr-2"></i> 附件(样品图片) <span class="text-red-500">*</span>
                    </h2>
                    <i class="fas fa-chevron-down text-gray-500 transition-transform duration-300"
                        id="attachmentSection-arrow"></i>
                </div>
                <div class="mt-4 transition-all duration-300" id="attachmentSection">
                    <div class="border-2 border-gray-300 rounded-lg p-6 text-center" id="uploadArea">
                        <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-3"></i>
                        <p class="text-gray-600 mb-3">点击下方按钮上传图片</p>
                        <p class="text-gray-400 text-sm">支持 JPG, PNG, PDF 格式，图片大小不超过 10MB</p>
                        <!-- 隐藏的原生图片输入框 -->
                        <input type="file" id="fileInput" accept=".jpg,.jpeg,.png,.pdf" multiple>
                        <!-- 上传按钮 -->
                        <button type="button" id="selectFileBtn"
                            class="mt-4 bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 px-4 rounded-lg transition duration-300 cursor-pointer outline-none">
                            <i class="fa fa-upload mr-1"></i> 选择图片
                        </button>
                        <!-- 错误提示 -->
                        <p class="error-text" id="errorMsg"></p>
                    </div>
                </div>

                <!-- 图片预览区域 -->
                <div id="previewSection">
                    <h3 class="text-gray-800 mb-2">已选择图片</h3>
                    <div id="previewList"></div>
                </div>
            </div>

            <!-- Actions -->
            <div class="flex flex-col gap-3">
                <button type="button" onclick="showConfirmModal()"
                    class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-3 px-4 rounded-lg font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all duration-300">
                    <i class="fas fa-paper-plane mr-2"></i> 提交委托
                </button>
                <button type="button" onclick="history.back()"
                    class="bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 px-4 rounded-lg font-semibold transition duration-300">
                    <i class="fas fa-arrow-left mr-2"></i> 返回
                </button>
            </div>
        </form>
    </div>

    <!-- Confirm Modal -->
    <div id="confirmModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
        <div class="bg-white rounded-2xl w-full max-w-sm mx-auto p-6 transform transition-all duration-300 scale-95 opacity-0"
            id="modalContent">
            <div class="text-center">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-question-circle text-blue-500 text-2xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-gray-800 mb-2">确认提交</h3>
                <p class="text-gray-600 mb-6">您确定要提交委托信息吗？</p>
                <div class="flex gap-3">
                    <button onclick="hideConfirmModal()"
                        class="flex-1 py-3 px-4 bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium rounded-lg transition duration-300">
                        取消
                    </button>
                    <button onclick="submitForm()"
                        class="flex-1 py-3 px-4 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white font-medium rounded-lg transition duration-300">
                        确认
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Modal -->
    <div id="loadingModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
        <div class="bg-white rounded-2xl w-full max-w-sm mx-auto p-6 text-center">
            <div class="w-16 h-16 border-4 border-blue-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-4">
            </div>
            <h3 class="text-xl font-semibold text-gray-800 mb-2">提交中</h3>
            <p class="text-gray-600">正在处理您的委托信息，请稍候...</p>
        </div>
    </div>

    <!-- Success Modal -->
    <div id="successModal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
        <div class="bg-white rounded-2xl w-full max-w-sm mx-auto p-6 transform transition-all duration-300 scale-95 opacity-0"
            id="successContent">
            <div class="text-center">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-check text-green-500 text-2xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-gray-800 mb-2">提交成功</h3>
                <p class="text-gray-600 mb-6">您的委托信息已成功提交！</p>
                <button onclick="gotoHistory()"
                    class="w-full py-3 px-4 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white font-medium rounded-lg transition duration-300">
                    查看历史记录
                </button>
            </div>
        </div>
    </div>

    <!-- Error Modal -->
    <div id="errorModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 hidden z-50">
        <div class="bg-white rounded-2xl w-full max-w-sm mx-auto p-6 transform transition-all duration-300 scale-95 opacity-0"
            id="errorContent">
            <div class="text-center">
                <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-exclamation-triangle text-red-500 text-2xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-gray-800 mb-2">提交失败</h3>
                <p class="text-gray-600 mb-6" id="errorMessage">提交过程中出现错误，请重试</p>
                <button onclick="hideErrorModal()"
                    class="w-full py-3 px-4 bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium rounded-lg transition duration-300">
                    确定
                </button>
            </div>
        </div>
    </div>

    <script>
        // 存储从后端获取的字段配置
        let fieldConfig = [];
        let fieldPathList = [];
        let submitUser = '';
        // API基础地址
        const API_BASE_URL = 'http://8.137.148.120:28081';

        let materialCode
        const orderId = new URLSearchParams(window.location.search);
        materialCode = orderId.get('orderId');
        // if (materialCode) {
        //     const response = fetch(`${API_BASE_URL}/order/get-data?materialCode=${materialCode}`);
        // }

        // 获取DOM元素
        const fileInput = document.getElementById('fileInput');
        const selectFileBtn = document.getElementById('selectFileBtn');
        const previewSection = document.getElementById('previewSection');
        const previewList = document.getElementById('previewList');
        const errorMsg = document.getElementById('errorMsg');
        const uploadBtn = document.getElementById('uploadBtn');
        const userInput = document.getElementById('userInput');
        const typeSelect = document.getElementById('typeSelect');

        // 字段映射关系，表单字段名 -> 后端fieldName
        const fieldMappings = {
            'wtdw': 'wtdw',          // 委托单位
            'wtdwdz': 'wtdwdz',    // 地址
            'wtdwlxr': 'wtdwlxr',    // 联系人
            'wtdwdh': 'wtdwdh',        // 联系电话
            'jljzdw': 'jljzdw', // 监理/见证单位
            'sgdw': 'sgdw', // 施工单位
            'gcmc': 'gcmc', // 工程名称
            'gcdd': 'gcdd', // 工程地点
            'gcbw': 'gcbw',   // 工程部位
            'qydd': 'qydd', // 取样地点
            'ypmc': 'ypmc',    // 样品名称
            'qyrq': 'qyrq',    // 取样日期
            'ggxh': 'ggxh', // 规格型号
            'ypsl': 'ypsl', // 样品数量
            'sybh': 'sybh',    // 送样编号
            'scdw': 'scdw',  // 生产单位
            'phbh': 'phbh',     // 批号/编号
            'dbsl': 'dbsl', // 代表数量
            'jcxm': 'jcxm',      // 检测项目
            'jclb': 'jclb',  // 检测类别
            'jcyj': 'jcyj',   // 检测依据
            'pdyj': 'pdyj', // 评定依据
            'ypcz': 'ypcz', // 样品处置
            'bz': 'bz'           // 备注
        };

        // 页面加载时获取字段配置
        document.addEventListener('DOMContentLoaded', function () {
            // 默认展开所有部分
            const sections = ['unitSection', 'projectSection', 'sampleSection', 'testSection', 'attachmentSection'];
            sections.forEach(sectionId => {
                const section = document.getElementById(sectionId);
                const arrow = document.getElementById(sectionId + '-arrow');
                section.classList.remove('hidden');
                arrow.classList.add('rotate-180');
            });

            // 获取字段配置
            if (materialCode) {
                fetchGetData()
            }
            else {
                fetchFieldConfig();
            }
        });

        // 从后端获取字段配置，增加跨域处理
        function fetchFieldConfig() {
            fetch(`${API_BASE_URL}/order/get-fields`, {
                method: 'GET',
                mode: 'cors', // 启用跨域
                headers: {
                    'Content-Type': 'application/json',
                    // 可以添加其他必要的请求头，如认证信息
                }
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.code === 403) {
                            throw new Error('没有访问权限，请先登录');
                        } else if (response.code === 404) {
                            throw new Error('请求的资源不存在');
                        } else if (response.code === 500) {
                            throw new Error('服务器内部错误');
                        } else if (response.code === 0) {
                            throw new Error('跨域请求被阻止，请检查后端CORS设置');
                        } else {
                            throw new Error(`获取字段配置失败: ${response.statusText}`);
                        }
                    }
                    return response.json();
                })
                .then(data => {
                    fieldConfig = data.data;
                    console.log('fieldConfig', fieldConfig);

                })
                .catch(error => {
                    console.error('获取字段配置出错:', error);
                    showErrorModal(error.message || '获取表单配置失败，请刷新页面重试');
                });
        }

        function fetchGetData() {
            fetch(`${API_BASE_URL}/order/get-data?materialCode=${materialCode}`, {
                method: 'GET',
                mode: 'cors', // 启用跨域
                headers: {
                    'Content-Type': 'application/json',
                    // 可以添加其他必要的请求头，如认证信息
                }
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.code === 403) {
                            throw new Error('没有访问权限，请先登录');
                        } else if (response.code === 404) {
                            throw new Error('请求的资源不存在');
                        } else if (response.code === 500) {
                            throw new Error('服务器内部错误');
                        } else if (response.code === 0) {
                            throw new Error('跨域请求被阻止，请检查后端CORS设置');
                        } else {
                            throw new Error(`获取字段配置失败: ${response.statusText}`);
                        }
                    }
                    return response.json();
                })
                .then(data => {
                    fieldConfig = data.data.fieldsValue;
                    console.log('字段配置获取成功', data.data.fieldsValue);
                    fieldConfig.forEach((item) => {
                        if (item.fieldAlias == '附件') {
                            selectedFiles = item.value.previewUrl
                        }
                    })
                    renderPreview();
                    populateForm(data.data.fieldsValue)
                })
                .catch(error => {
                    console.error('获取字段配置出错:', error);
                    showErrorModal(error.message || '获取表单配置失败，请刷新页面重试');
                });
        }

        // 填充表单数据
        function populateForm(data) {
            // 获取表单元素
            const form = document.getElementById('delegationForm');

            // 遍历数据并填充到表单字段
            for (const [key, value] of Object.entries(data)) {
                const field = document.getElementsByName(value.fieldName)
                if (field.length > 0) {
                    // 根据字段类型设置值
                    switch (field.type) {
                        case 'checkbox':
                            field.checked = value;
                            break;
                        case 'radio':
                            // 处理单选按钮组
                            const radioGroup = form.querySelectorAll(`input[name="${key}"]`);
                            radioGroup.forEach(radio => {
                                radio.checked = radio.value === value;
                            });
                            break;
                        default:
                            field[0].value = value.value;

                    }
                }
            }

            // 特殊处理附件预览（如果有已上传的文件）
            if (data.attachments && data.attachments.length > 0) {
                previewExistingAttachments(data.attachments);
            }
        }

        function toggleSection(sectionId) {
            const section = document.getElementById(sectionId);
            const arrow = document.getElementById(sectionId + '-arrow');

            // 切换显示/隐藏
            if (section.classList.contains('hidden')) {
                // 显示部分
                section.classList.remove('hidden');
                setTimeout(() => {
                    section.classList.remove('opacity-0');
                }, 10);
                arrow.classList.add('rotate-180');
            } else {
                // 隐藏部分
                section.classList.add('opacity-0');
                arrow.classList.remove('rotate-180');
                setTimeout(() => {
                    section.classList.add('hidden');
                }, 300);
            }
        }

        function showConfirmModal() {
            const modal = document.getElementById('confirmModal');
            const modalContent = document.getElementById('modalContent');
            modal.classList.remove('hidden');
            if (selectedFiles.length > 0) {
                uploadFiles()
            }
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        function hideConfirmModal() {
            const modal = document.getElementById('confirmModal');
            const modalContent = document.getElementById('modalContent');
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }

        function showLoadingModal() {
            const modal = document.getElementById('loadingModal');
            modal.classList.remove('hidden');
        }

        function hideLoadingModal() {
            const modal = document.getElementById('loadingModal');
            modal.classList.add('hidden');
        }

        function showSuccessModal() {
            const modal = document.getElementById('successModal');
            const modalContent = document.getElementById('successContent');
            modal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        function showErrorModal(message) {
            const modal = document.getElementById('errorModal');
            const modalContent = document.getElementById('errorContent');
            const errorMessage = document.getElementById('errorMessage');

            if (message) {
                errorMessage.textContent = message;
            }

            modal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        function hideErrorModal() {
            const modal = document.getElementById('errorModal');
            const modalContent = document.getElementById('errorContent');
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }

        function gotoHistory() {
            window.location.href = 'history.html';
        }

        // 转换表单数据为后端需要的格式
        function convertFormData(formData) {
            const result = [];
            console.log('formData123123', formData, formData.entries());

            // 遍历所有表单字段
            for (const [formField, value] of formData.entries()) {
                // 跳过空值
                if (!value) continue;
                if (formField == 'wtdwdh') {
                    submitUser = value
                }
                // 获取对应的后端fieldName
                const backendFieldName = fieldMappings[formField];
                if (!backendFieldName) continue;
                console.log('fieldConfig', fieldConfig);

                // 查找对应的字段配置
                const fieldInfo = fieldConfig.find(field => field.fieldName === backendFieldName);
                if (fieldInfo && materialCode) {
                    // 添加到结果数组
                    result.push({
                        fieldCode: fieldInfo.fieldCode,
                        fieldName: fieldInfo.fieldName,
                        fieldAlias: fieldInfo.fieldAlias,
                        indicatorCode: fieldInfo.indicatorCode,
                        id: fieldInfo.id,
                        value: value
                    });
                } else {
                    // 添加到结果数组
                    result.push({
                        fieldCode: fieldInfo.fieldCode,
                        fieldName: fieldInfo.fieldName,
                        fieldAlias: fieldInfo.fieldAlias,
                        indicatorCode: fieldInfo.indicatorCode,
                        value: value
                    });
                }
            }

            return result;
        }

        async function submitForm() {
            // 隐藏确认对话框，显示加载框
            hideConfirmModal();
            showLoadingModal();
            console.log('fieldConfig', fieldConfig);
            try {
                // 检查是否已获取字段配置
                if (fieldConfig.length === 0) {
                    throw new Error('未获取到表单配置，请刷新页面重试');
                }

                // 获取表单数据
                const form = document.getElementById('delegationForm');
                const formData = new FormData(form);
                console.log('formData', formData.entries().wtdwdh);

                // 转换数据格式
                const submitData = convertFormData(formData);

                console.log('提交的数据:', submitData, fieldPathList);

                // 检查是否有数据需要提交
                if (submitData.length === 0) {
                    throw new Error('没有可提交的数据，请填写表单');
                }
                submitData.push({
                    fieldCode: "aef08d5984b2472f84be112b777893a6",
                    fieldName: "wtbh",
                    fieldAlias: "委托编号",
                    value: "",
                    indicatorCode: 'bc767b173ab345bab960f129ff3d489a',
                })
                submitData.push({
                    fieldCode: "279e2cfeba4e4079bf82b178c83bbc78",
                    fieldName: "fj",
                    fieldAlias: "附件",
                    value: fieldPathList,
                    indicatorCode: 'f147f67aa03247ef8f1ffc1194663b09',
                })
                submitData.push({
                    fieldCode: "1135f48ce1c34e1c976b1d0761a17345",
                    fieldName: "ypbh",
                    fieldAlias: "样品编号",
                    value: "",
                    indicatorCode: 'bc767b173ab345bab960f129ff3d489a',
                })
                localStorage.setItem('userPhone', submitUser)
                let response
                // 提交到后端，增加跨域处理
                if (materialCode) {
                    response = await fetch(`${API_BASE_URL}/order/modify`, {
                        method: 'POST',
                        mode: 'cors', // 启用跨域
                        headers: {
                            'Content-Type': 'application/json',
                            // 可以添加其他必要的请求头，如认证信息
                        },
                        body: JSON.stringify({ submitUser: submitUser, fieldsValue: submitData, materialCode: materialCode }),
                    });
                } else {
                    response = await fetch(`${API_BASE_URL}/order/submit`, {
                        method: 'POST',
                        mode: 'cors', // 启用跨域
                        headers: {
                            'Content-Type': 'application/json',
                            // 可以添加其他必要的请求头，如认证信息
                        },
                        body: JSON.stringify({ submitUser: submitUser, fieldsValue: submitData }),
                    });
                }


                // 隐藏加载框
                hideLoadingModal();

                if (!response.ok) {
                    if (response.code === 403) {
                        throw new Error('没有提交权限，请先登录');
                    } else if (response.code === 400) {
                        throw new Error('提交的数据格式不正确');
                    } else if (response.code === 500) {
                        throw new Error('服务器内部错误');
                    } else if (response.code === 0) {
                        throw new Error('跨域请求被阻止，请检查后端CORS设置');
                    } else {
                        throw new Error(`提交失败: ${response.statusText}`);
                    }
                }

                // 显示成功对话框
                showSuccessModal();

            } catch (error) {
                console.error('提交出错:', error);
                // 隐藏加载框，显示错误对话框
                hideLoadingModal();
                showErrorModal(error.message || '提交失败，请重试');
            }
        }


        //图片上传
        // 存储已选择的文件
        let selectedFiles = [];

        // 允许的文件类型和大小限制
        const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'application/pdf'];
        const MAX_SIZE = 10 * 1024 * 1024; // 10MB
        const FILE_EXT_MAP = {
            'image/jpeg': 'fa-file-image-o',
            'image/png': 'fa-file-image-o',
            'application/pdf': 'fa-file-pdf-o'
        };

        // 显示错误信息
        function showError(msg) {
            errorMsg.textContent = msg;
            errorMsg.style.display = 'block';
            setTimeout(() => {
                errorMsg.style.display = 'none';
            }, 3000);
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
        }

        // 验证文件
        function validateFile(file) {
            if (!ALLOWED_TYPES.includes(file.type)) {
                showError(`不支持的文件格式：${file.name}，仅支持JPG、PNG、PDF`);
                return false;
            }
            if (file.size > MAX_SIZE) {
                showError(`文件${file.name}过大（${formatFileSize(file.size)}），最大支持10MB`);
                return false;
            }
            return true;
        }

        // 渲染文件预览
        function renderPreview() {
            console.log('selectedFiles', selectedFiles);

            previewList.innerHTML = '';
            if (selectedFiles.length === 0) {
                previewSection.style.display = 'none';
                return;
            }
            previewSection.style.display = 'block';
                            // 类型：${file.type.split('/')[1].toUpperCase()} | 大小：${formatFileSize(file.size)}
            selectedFiles.forEach((file, index) => {
                const previewCard = document.createElement('div');
                previewCard.className = 'preview-card';
                previewCard.innerHTML = `
                    <div class="preview-icon">
                        <i class="fa ${FILE_EXT_MAP[file.type]}"></i>
                    </div>
                    <div class="preview-info">
                        <div class="preview-name">图片</div>
                        <div class="preview-meta">
                            类型：图片
                        </div>
                    </div>
                    <div class="preview-actions" data-index="${index}">
                        <i class="fa fa-trash"></i> 删除
                    </div>
                `;
                previewList.appendChild(previewCard);
            });
            console.log('document',document.querySelectorAll('.preview-actions'));
            
            document.querySelectorAll('.preview-actions').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const index = parseInt(e.currentTarget.dataset.index);
                    selectedFiles.splice(index, 1);
                    renderPreview();
                });
            });
        }

        // 处理文件选择
        function handleFileSelect(files) {
            Array.from(files).forEach(file => {
                if (!validateFile(file)) return;

                const isDuplicate = selectedFiles.some(existFile =>
                    existFile.name === file.name && existFile.size === file.size && existFile.lastModified === file.lastModified
                );
                if (isDuplicate) {
                    showError(`文件${file.name}已添加，无需重复选择`);
                    return;
                }

                selectedFiles.push(file);
            });
            renderPreview();
        }

        // 上传文件
        function uploadFiles() {
            // 验证用户和类型信息
            // if (!userInput.value.trim()) {
            //     showError('请输入用户信息');
            //     return;
            // }

            // if (!typeSelect.value) {
            //     showError('请选择文件类型');
            //     return;
            // }

            if (selectedFiles.length === 0) {
                showError('请先选择文件');
                return;
            }

            // 显示上传中状态
            // uploadBtn.disabled = true;
            // uploadBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 上传中...';

            // 遍历所有文件，逐个上传
            const uploadPromises = selectedFiles.map(file => {
                const formData = new FormData();
                console.log('form', '18111888018');
                formData.append('user', document.getElementsByName('wtdwdh')[0].value);
                formData.append('file', file);
                formData.append('type', 'ORDER_ATTACHMENT');
                return fetch('http://8.137.148.120:28081/file/upload', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        // 'Content-Type': 'application/json',
                        Authorization: ''
                        // 可以添加其他必要的请求头，如认证信息
                    }
                    // 跨域设置
                    // credentials: 'include'
                }).then(response => {
                    if (!response.ok) {
                        // throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    console.log('data', response);
                    return response.json().then(data => ({
                        success: true,
                        data,
                        fileName: file.name
                    })

                    ).catch(() => ({
                        success: true,
                        data: '上传成功',
                        fileName: file.name
                    }));
                }).catch(error => ({
                    success: false,
                    error: error.message,
                    fileName: file.name
                }));
            });

            // 处理所有上传结果
            Promise.all(uploadPromises).then(results => {
                const successFiles = results.filter(r => r.ok).map(r => r.fileName);
                const failFiles = results.filter(r => !r.ok).map(r => r.fileName);
                fieldPathList = results.filter(r => !r.ok).map(r => r.data.data.fileCode);
                console.log('fieldPathList', fieldPathList);

                let message = '';
                if (successFiles.length > 0) {
                    message += `成功上传 ${successFiles.length} 个文件: ${successFiles.join(', ')}\n`;
                }
                if (failFiles.length > 0) {
                    message += `上传失败 ${failFiles.length} 个文件: ${failFiles.join(', ')}`;
                }

                // alert(message);

                // 清除已成功上传的文件
                if (successFiles.length > 0) {
                    selectedFiles = selectedFiles.filter(file =>
                        !successFiles.includes(file.name)
                    );
                    renderPreview();
                }
            }).catch(error => {
                showError(`上传过程出错: ${error.message}`);
            }).finally(() => {
                // 恢复按钮状态
                // uploadBtn.disabled = false;
                // uploadBtn.innerHTML = '<i class="fa fa-send mr-1 mb-5"></i> 确认上传';
            });
        }

        // 绑定事件监听
        selectFileBtn.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            handleFileSelect(e.target.files);
            fileInput.value = '';
        });

        // 确认上传
        // uploadBtn.addEventListener('click', uploadFiles);
    </script>
</body>

</html>